const xss = require('xss')
const blogs = require('../dao/blogs')

const getList = (author, keyword) => {
  return blogs.getList(author, keyword).then(rows => {
    return rows
  })
}

const getDetail = (id) => {
  return blogs.getDetail(id).then(rows => {
    return rows[0]
  })
}

const newBlog = (blogData = {}) => {
  // blogData 是一个博客对象，包含 title content author 属性
  // 预防 xss 攻击
  const title = xss(blogData.title)
  const content = (blogData.content)
  const author = blogData.author
  const createTime = Date.now()

  // 执行插入操作返回的 rows 是一个对象，里面有新插入的文档的 id
  return blogs.newBlog(title, content, author, createTime).then(rows => {
    return {
      id: rows.insertId
    }
  })
}

const  updateBlog = (id, blogData = {}) => {
  const title = blogData.title
  const content = blogData.content

  // 执行更新操作返回的 rows 是一个对象
  return blogs.updateBlog(id, title, content).then(rows => {
    if (rows.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}

const delBlog = (id, author) => {
  // 删除时添加 author 字段保证登录后才能删除博客，且只删除自己的博客
  return blogs.delBlog(id, author).then(rows => {
    if (rows.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}



module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
}
